import { Component, OnInit } from '@angular/core';
import { Router,ActivatedRoute,NavigationExtras } from '@angular/router';
import {HttpClient,HttpHeaders, HttpErrorResponse} from "@angular/common/http";
import { ToastController } from '@ionic/angular';
import {environment} from 'src/environments/environment';
import { EncryptService } from '@services/encrypt.service';
import { AuthTokenService } from '@services/auth-token.service';
import { CommonResponse,VerificationType,ToastColor,CommonService,AppVerificationCode,AppParam} from '@services/common-service.service'
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { TranslateService } from '@ngx-translate/core';
import { DefaultLanguageService } from '@services/default-language.service';

@Component({
  selector: 'app-input-verification-code',
  templateUrl: './input-verification-code.page.html',
  styleUrls: ['./input-verification-code.page.scss'],
})
export class InputVerificationCodePage implements OnInit {

  public defaultSmsCountDown:number;

  public smsCountDown:number;

  public sendView:boolean = false;

  public appUserId:string;

  public loading:boolean = false;

  public i18n:any;
  constructor(private router: Router,
    private route: ActivatedRoute,
    public http:HttpClient,
    private encryptService:EncryptService,
    private authTokenService:AuthTokenService,
    private commonService:CommonService,
    private defaultLanguageService:DefaultLanguageService,
    private translate: TranslateService) { 
      this.i18n = this.commonService.initTranslate(['auth.reset-pwd.input-verification-code']); 
      this.defaultSmsCountDown = parseInt(this.commonService.getAppParamFromCache(AppParam.SMS_COUNT_DOWN));
      this.smsCountDown = this.defaultSmsCountDown; 
  }


  public validateForm:FormGroup;
  ngOnInit() {
    this.route.queryParams.subscribe((data)=>{
      this.appUserId = data.appUserId;
      this.sendAppVerificationCode();
    })
    this.validateForm = new FormGroup({
      'verificationCode':new FormControl('',[
        Validators.required
      ]),
    });
  }

  get verificationCode(){return this.validateForm.get('verificationCode');}

  signIn(){
    this.router.navigate(['/auth/signin-password']);
  }

  private countDown(){
    this.sendView = false;
    var id = setInterval(() => {
      this.smsCountDown--;
      if(this.smsCountDown == 0){
        this.smsCountDown = this.defaultSmsCountDown;
        clearInterval(id);
        this.sendView = true;
      }
    }, 1000);
  }

  sendAppVerificationCode(){
    if(!this.appUserId){return false;}
    let sendAppVerificationCode:AppVerificationCode = {
      appUserId:this.appUserId,
      mobileNumber:'',
      verificationType:VerificationType.UPDATE_USER_PASSWORD_BEFORE_LOGIN,
      verificationCode:'',
      appCode:environment.APP_CODE
    }
    let currentTime = new Date().getTime();
    let sign1 = this.encryptService.md5Ecrypt(this.authTokenService.getDeviceId()+currentTime);
    let sign2 = this.encryptService.rsaEcrypt(this.authTokenService.getDeviceId()+","+currentTime);
    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json','sign1':sign1,'sign2':sign2 })
    };
    var api = "/scm/app/sendAppVerificationCode.do";
    this.http.post(api,sendAppVerificationCode,httpOptions).subscribe((response:CommonResponse) => {
      this.countDown();
    },(errorResponse:HttpErrorResponse)=>{
      this.commonService.errorRespCommonToast(errorResponse,this.i18n);
    })
  }

  checkAppVerificationCode(){
    this.loading = true;
    let checkAppVerificationCode:AppVerificationCode = {
      appUserId:this.appUserId,
      verificationCode:this.validateForm.value.verificationCode,
      verificationType:VerificationType.UPDATE_USER_PASSWORD_BEFORE_LOGIN,
      mobileNumber:'',
      appCode:environment.APP_CODE
    }
    let currentTime = new Date().getTime();
    let sign1 = this.encryptService.md5Ecrypt(this.authTokenService.getDeviceId()+currentTime);
    let sign2 = this.encryptService.rsaEcrypt(this.authTokenService.getDeviceId()+","+currentTime);
    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json','sign1':sign1,'sign2':sign2 })
    };
    var api = "/scm/app/checkAppVerificationCode.do";
    this.http.post(api,checkAppVerificationCode,httpOptions).subscribe((response:CommonResponse) => {
      if(response.isSuccess){
        if(response.responseBody.isPass){
          let navigationExtras: NavigationExtras = {
            queryParams: {
              'appUserId':this.appUserId
            }
          };
          this.router.navigate(['/auth/reset-pwd/input-password'],navigationExtras);
        }else{
          this.commonService.commonToast(ToastColor.warning,this.i18n.check_failed);
        }
      }else{
        this.commonService.commonToast(ToastColor.warning);
      }
      this.loading = false;
    },(errorResponse:HttpErrorResponse)=>{
      this.commonService.errorRespCommonToast(errorResponse,this.i18n);
      this.loading = false;
    });
  }

  toInputPassword(){
    if(this.validateForm.invalid){
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
      return false;
    }
    this.checkAppVerificationCode();
  }
}
